<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改考场安排')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: bootstrap-select-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-examSchedule-edit" th:object="${examRoomSchedule}">
            <input name="id" th:field="*{id}" type="hidden">
            <div class="form-group">    
                <label class="col-sm-2 control-label is-required">场次编号：</label>
                <div class="col-sm-4">
                    <input name="examId" th:field="*{examId}" class="form-control" type="text" required>
                </div>
                <label class="col-sm-2 control-label is-required">名称：</label>
                <div class="col-sm-4">
                    <input name="name" th:field="*{name}" class="form-control" type="text" required>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-2 control-label is-required">年级：</label>
                <div class="col-sm-4">
                    <input id='gradeName' name='gradeName' th:field="*{gradeName}" class="form-control" type="hidden">
                    <select class='form-control selectpicker' data-live-search="true" id='gradeId' name='gradeId' th:field="*{gradeId}" required>
                        <option th:selected="${gradeId eq c.id}" th:each="c:${grades}" th:value="${c.id}" th:text="${c.gradeName}"></option>
                    </select>
                </div>
                <label class="col-sm-2 control-label is-required">学期：</label>
                <div class="col-sm-4">
                    <select class='form-control selectpicker' data-live-search="true" name="semester" th:with="type=${@dict.getType('sc_term_type')}" required>
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:selected="${semester eq dict.dictValue}"></option>
                    </select>
                </div>

            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">总人数：</label>
                <div class="col-sm-4">
                    <input name="total" th:field="*{total}" class="form-control" type="number" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">考试开始日期：</label>
                <div class="col-sm-4">
                    <div class="input-group date">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        <input name="examTime" th:value="${#dates.format(examRoomSchedule.examTime, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text">
                    </div>
                </div>

                <label class="col-sm-2 control-label">考试结束日期：</label>
                <div class="col-sm-4">
                    <div class="input-group date">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        <input name="examEnd" th:value="${#dates.format(examRoomSchedule.examEnd, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <button type="button" class="btn btn-info btn-xs" onclick="selectFixed()">选择考场</button>
                <div id="add_select">
                    <table id="room_table" class="table table-bordered"></table>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-select-js" />
    <script th:inline="javascript">
        var prefix = ctx + "school/examSchedule";
        var prefix2 = ctx + "school/examRoomClasses";
        $("#form-examSchedule-edit").validate({
            focusCleanup: true
        });
        var examRoomSchedule = [[${examRoomSchedule}]]

        var selectRommId = []

        $(function() {
            $("#room_table").bootstrapTable({
                uniqueId: "id",
                columns: [
                    {
                        field: 'id',
                        title: 'Id',
                        visible: false
                    },
                    {
                        field: 'rRid',
                        title: 'rId',
                        visible: false
                    },
                    {
                        field: 'roomId',
                        title: '考场编号'
                    },
                    {
                        field: 'location',
                        title: '考场位置'
                    },
                    {
                        field: 'numbers',
                        title: '容纳人数'
                    },
                    {
                        field: 'orderNum',
                        title: '排序'
                    }, {
                        title: '操作',
                        align: 'center',
                        formatter: function(value, row, index) {
                            var actions = [];
                            actions.push('<a class="btn btn-danger btn-xs " href="javascript:void(0)" onclick="remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
                            return actions.join('');
                        }
                    }
                    ]
            })
            console.log(examRoomSchedule)
            $("#room_table").bootstrapTable("load",examRoomSchedule.list);
        });
        
        function remove(id) {

            if(id>0){
                //执行数据库删除
                var uri = prefix2+"/remove"
                var data = {ids:id+""}
                $.ajax({
                    type: "post",
                    url:uri,
                    async:false,
                    dataType: "json",
                    data:data,
                    success: function(res){
                        console.log(res)
                        if(res.code ==0)
                            delTableRowById(id)
                        else{
                            $.modal.alertWarning(res.msg);
                        }
                    }
                });
            }else{
                delTableRowById(id);
            }
        }

        function delTableRowById(id) {
            var rows = $('#room_table').bootstrapTable('getRowByUniqueId',id);//行的数据
            var index = selectRommId.indexOf(rows.roomId);
            selectRommId.splice(index, 1)
            $("#room_table").bootstrapTable('removeByUniqueId', id);
        }



        function submitHandler() {
            $("#gradeName").val($("#gradeId option:selected").text());
            if ($.validate.form()) {
                var roomsList = $("#room_table").bootstrapTable('getData');
                var data = $('#form-examSchedule-edit').serializeJSON();
                //var answerList = JSON.stringify( roomsList );
                data.list = [];
                if(roomsList != null){
                    var m=0;
                    for (let i = 0; i < roomsList.length; i++) {
                        var id = roomsList[i].id;
                        console.log(id);
                        if(id<0){
                            data["list["+i+"].rId"]=roomsList[i].id;
                            data["list["+i+"].rRid"]=roomsList[i].rid;
                            data["list["+m+"].roomId"]=roomsList[i].roomId;
                            data["list["+m+"].location"]=roomsList[i].location;
                            data["list["+m+"].numbers"]=roomsList[i].numbers;
                            data["list["+m+"].orderNum"]=roomsList[i].orderNum;
                            m++;
                        }
                    }
                }
                $.operate.save(prefix + "/edit", data);
            }


        }

        $("input[name='examTime']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });
        $("input[name='examEnd']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        function selectFixed() {
            var url = ctx + "school/roomInfo/getRoomList";
            var options = {
                title: '选择固定考场',
                width: "800",
                url: url,
                callBack: doSubmit
            };
            $.modal.openOptions(options);
        }

        function doSubmit(index, layero){
            var table = layero.find("iframe")[0].contentWindow.$.table;
            var ids = table.selectColumns("id");
            if(ids.length == 0){
                $.modal.alertWarning("请选择一条记录");
                return;
            }
            var datas = $("#room_table").bootstrapTable("getOptions").data;
            var index1 = datas.length;
            var rids = table.selectColumns("id");
            var roomIds = table.selectColumns("roomId");
            var locations = table.selectColumns("location");
            var personNumbers = table.selectColumns("personNumber");
            for(let i=0;i<ids.length;i++){
                var randomId = -(100 + ~~(Math.random() * 100));
                var rid = roomIds[i];
                if(rIdExit(rid)==0){
                    $("#room_table").bootstrapTable('insertRow', {
                        index: index1+i, // 你想插入到哪，0表示第一行
                        row: {
                            id:randomId,
                            rid:rids[i],
                            roomId: rid,
                            location: locations[i],
                            numbers: personNumbers[i],
                            orderNum:  1,
                        }
                    });
                    selectRommId.push(rid);
                }

            }
            layer.close(index);
        }

        function  rIdExit(rId) {
            var ex = 0;
            var len = selectRommId.length
            for(var im = 0;im<len;im++){
                var sId = selectRommId[im];
                if(sId == rId){
                    ex = 1;
                    break;
                }
            }
            return ex;
        }

    </script>
</body>
</html>